package com.stylefeng.guns.core.util;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;  
import javax.net.ssl.TrustManager;
public class HttpUtil {

	public synchronized static String doGet(String urlAddress,Map<String, Object> params,String encoding){
		String getUrl =initParams(urlAddress,params,encoding);
		String response = "";
		try{
			URL url =new URL(getUrl);
			HttpURLConnection uRLConnection = (HttpURLConnection)url.openConnection();
			InputStream is = uRLConnection.getInputStream();
			BufferedReader br =new BufferedReader(new InputStreamReader(is));			
			String readLine =null;
			while((readLine =br.readLine()) !=null){			
				response = response + readLine;
			}
			br.close();
			uRLConnection.disconnect();
			
		}catch(Exception e) {
			e.printStackTrace();
			
		}
		return response;
	}
	public synchronized static void downFile(String urlAddress,Map<String, Object> params,String encoding,OutputStream  outfileRespone,OutputStream  outfile){
		String content="";
		try{
			if(params!=null && !params.isEmpty()){			
				for(Entry<String, Object> entry:params.entrySet() ){
					String name=entry.getKey();
					String value="";
					if(entry.getValue()!=null){					
						value=entry.getValue().toString();
						value=URLEncoder.encode(URLEncoder.encode(value, encoding),encoding);
					}
					content+=name+"="+value+"&";
				}
			}		
			if(content.trim().length()>0){
				content=content.substring(0,content.length()-1);
			}
			
			URL url =new URL(urlAddress);
			HttpURLConnection uRLConnection = (HttpURLConnection)url.openConnection();
			uRLConnection.setDoInput(true);
			uRLConnection.setDoOutput(true);
			uRLConnection.setRequestMethod("POST");
			uRLConnection.setUseCaches(false);
			uRLConnection.setInstanceFollowRedirects(false);
			uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			uRLConnection.connect();
	        
			DataOutputStream out =new DataOutputStream(uRLConnection.getOutputStream());
			
			out.writeBytes(content);
			out.flush();
			out.close();
	
			InputStream is = uRLConnection.getInputStream();
			BufferedReader br =new BufferedReader(new InputStreamReader(is));
			int len = 0;  
            byte[] buffer = new byte[1024];              
            while ((len = is.read(buffer)) != -1) {              	
            	if(outfile!=null){
            		outfile.write(buffer, 0, len); 
            	}
            	if(outfileRespone!=null){
            		outfileRespone.write(buffer, 0, len); 
            	}
            }  
			br.close();
			if(outfile!=null){
				outfile.flush();	
				outfile.close();
			}
			if(outfileRespone!=null){				
				outfileRespone.flush();	
				outfileRespone.close();
			}
			uRLConnection.disconnect();		 
		}catch(Exception e) {
			e.printStackTrace();		
		}		
	}
	public synchronized static String doPost(String urlAddress,String content){
		String response = "";
		try{
			
			
			URL url =new URL(urlAddress);
			HttpURLConnection uRLConnection = (HttpURLConnection)url.openConnection();
			uRLConnection.setDoInput(true);
			uRLConnection.setDoOutput(true);
			uRLConnection.setRequestMethod("POST");
			uRLConnection.setUseCaches(false);
			uRLConnection.setInstanceFollowRedirects(false);
			uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");		
			uRLConnection.connect();
			if(content!=null && content.length()>0){				
				DataOutputStream out =new DataOutputStream(uRLConnection.getOutputStream());				
				out.write(content.getBytes("utf-8"));
				out.flush();
				out.close();
			}
			
			InputStream is = uRLConnection.getInputStream();
			BufferedReader br =new BufferedReader(new InputStreamReader(is,"UTF-8"));
			
			String readLine =null;
			while((readLine =br.readLine()) !=null){			
				response = response + readLine;
			}			
			br.close();
			uRLConnection.disconnect();		 
		}catch(Exception e) {
			e.printStackTrace();		
		}
		return response;
		
	}
	public synchronized static String doPost(String urlAddress,Map<String, Object> params,String encoding){
		String response = "";
		String content="";
		try{
			if(params!=null && !params.isEmpty()){			
				for(Entry<String, Object> entry:params.entrySet() ){
					String name=entry.getKey();
					String value="";
					if(entry.getValue()!=null){					
						value=entry.getValue().toString();
						value=URLEncoder.encode(URLEncoder.encode(value, encoding),encoding);
					}
					content+=name+"="+value+"&";
				}
			}		
			if(content.trim().length()>0){
				content=content.substring(0,content.length()-1);
			}
			
			URL url =new URL(urlAddress);
			HttpURLConnection uRLConnection = (HttpURLConnection)url.openConnection();
			uRLConnection.setDoInput(true);
			uRLConnection.setDoOutput(true);
			uRLConnection.setRequestMethod("POST");
			uRLConnection.setUseCaches(false);
			uRLConnection.setInstanceFollowRedirects(false);
			uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");		
			uRLConnection.connect();
			
			DataOutputStream out =new DataOutputStream(uRLConnection.getOutputStream());
			
			out.writeBytes(content);
			out.flush();
			out.close();
	
			InputStream is = uRLConnection.getInputStream();
			BufferedReader br =new BufferedReader(new InputStreamReader(is,"UTF-8"));
			
			String readLine =null;
			while((readLine =br.readLine()) !=null){			
				response = response + readLine;
			}			
			br.close();
			uRLConnection.disconnect();		 
		}catch(Exception e) {
			e.printStackTrace();		
		}
		return response;
		
	}
	public synchronized static String doPostBody(String urlAddress,String params){
		String response = "";
		try{

			URL url =new URL(urlAddress);
			HttpURLConnection uRLConnection = (HttpURLConnection)url.openConnection();
			uRLConnection.setDoInput(true);
			uRLConnection.setDoOutput(true);
			uRLConnection.setRequestMethod("POST");
			uRLConnection.setUseCaches(false);
			uRLConnection.setInstanceFollowRedirects(false);
			uRLConnection.setRequestProperty("Content-Type", "application/json");
			uRLConnection.connect();

			OutputStream outputStream = uRLConnection.getOutputStream();
			outputStream.write(params.getBytes("UTF-8"));
			if (outputStream!=null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			InputStream is = uRLConnection.getInputStream();
			BufferedReader br =new BufferedReader(new InputStreamReader(is,"UTF-8"));

			String readLine =null;
			while((readLine =br.readLine()) !=null){
				response = response + readLine;
			}
			br.close();
			uRLConnection.disconnect();
		}catch(Exception e) {
			e.printStackTrace();
		}
		return response;

	}
	/**
	 * 通过post请求发送文本
	 * @param urlAddress
	 * @param xmlContent
	 * @return
	 */
	public synchronized static String doPostWx(String urlAddress,String xmlContent){
		    String response = "";
		    try{
			    //微信
		        URL httpUrl = new URL(urlAddress);
		        HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
		        httpURLConnection.setRequestProperty("Host", "api.mch.weixin.qq.com");	 
		        //httpURLConnection.setRequestProperty("Content-Type", "application/octet-stream");
		        httpURLConnection.setDoOutput(true);
		        httpURLConnection.setRequestMethod("POST");
		        httpURLConnection.setConnectTimeout(10*1000);
		        httpURLConnection.setReadTimeout(10*1000);
		        httpURLConnection.connect();	        
		        
		        OutputStream outputStream = httpURLConnection.getOutputStream();
		        outputStream.write(xmlContent.getBytes("UTF-8"));
		        if (outputStream!=null) {
		            try {
		                outputStream.close();
		            } catch (IOException e) {
		                e.printStackTrace();
		            }
		        }
		        
		        //获取内容
		        InputStream inputStream = httpURLConnection.getInputStream();
		        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
		        final StringBuffer stringBuffer = new StringBuffer();
		        String line = null;
		        while ((line = bufferedReader.readLine()) != null) {
		            stringBuffer.append(line);
		        }
		        response = stringBuffer.toString();
		        if (stringBuffer!=null) {
		            try {
		                bufferedReader.close();
		            } catch (IOException e) {
		                e.printStackTrace();
		            }
		        }
		        if (inputStream!=null) {
		            try {
		                inputStream.close();
		            } catch (IOException e) {
		                e.printStackTrace();
		            }
		        }
		       
		    }catch(Exception e) {
				e.printStackTrace();		
			}
	        return response;
	}
	
	/**
	 * 发送httpS Post 请求
	 * @param urlAddress
	 * @param xmlContent
	 * @param keyPsw 证书密码
	 * @param filePath 证书地址
	 * @return
	 */
	public synchronized static String doPostWxSSL(String urlAddress,String xmlContent,String keyPsw,String filePath,String mechid){
		    String response = "";
		    try{
		    	 
		    	char[] password =keyPsw.toCharArray();
		        // 实例化密钥库 & 初始化密钥工厂
		    	KeyStore keyStore = KeyStore.getInstance("PKCS12");  
		    	File f=new File(filePath);
		    	if( f.exists()){
		    		//System.out.println("dddd");
		    	}
	            FileInputStream instream = new FileInputStream(new File(filePath));  
	            try {  
	                keyStore.load(instream,password);  
	            }finally {  
	                instream.close();  
	            }  
	            
	            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	            kmf.init(keyStore, password);
	            TrustManager[] tm = { new MyX509TrustManager() };    
	            SSLContext sslContext = SSLContext.getInstance("TLS");   
	            sslContext.init(kmf.getKeyManagers(), tm, new SecureRandom());
	           
	            SSLSocketFactory ssf = sslContext.getSocketFactory();    
	            
			    //微信
		        URL httpUrl = new URL(urlAddress);
		        HttpsURLConnection httpURLConnection = (HttpsURLConnection) httpUrl.openConnection();
		        httpURLConnection.setSSLSocketFactory(ssf);		       
		        httpURLConnection.setDoOutput(true);    
		        httpURLConnection.setDoInput(true);    
		        httpURLConnection.setUseCaches(false);   
		        httpURLConnection.setRequestMethod("POST");
		        httpURLConnection.setConnectTimeout(10*1000);
		        httpURLConnection.setReadTimeout(10*1000);
		        httpURLConnection.setRequestProperty("Content-Type", "text/xml");
		        httpURLConnection.setRequestProperty("User-Agent", "wxpay sdk java v1.0 " + mechid);  
		        httpURLConnection.connect();	        
		        
		        OutputStream outputStream = httpURLConnection.getOutputStream();
		        outputStream.write(xmlContent.getBytes("UTF-8"));
		        if (outputStream!=null) {
		            try {
		                outputStream.close();
		            } catch (IOException e) {
		                e.printStackTrace();
		            }
		        }
		        
		        //获取内容
		        InputStream inputStream = httpURLConnection.getInputStream();
		        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
		        final StringBuffer stringBuffer = new StringBuffer();
		        String line = null;
		        while ((line = bufferedReader.readLine()) != null) {
		            stringBuffer.append(line);
		        }
		        response = stringBuffer.toString();
		        if (stringBuffer!=null) {
		            try {
		                bufferedReader.close();
		            } catch (IOException e) {
		                e.printStackTrace();
		            }
		        }
		        if (inputStream!=null) {
		            try {
		                inputStream.close();
		            } catch (IOException e) {
		                e.printStackTrace();
		            }
		        }
		       
		    }catch(Exception e) {
				e.printStackTrace();		
			}
	        return response;
	}

	/**
	 * 通过HttpURLConnection Post 上传文件
	 * @param fileList
	 * @param actionUrl
	 * @param pramsMap
	 * @return
	 * @throws Exception
	 */
	public synchronized static String uploadFileByPost(List fileList, String actionUrl,Map<String,String> pramsMap) throws Exception {
		/*-----------------------------7da2e536604c8    
		Content-Disposition: form-data; name="username"    
		     
		hello word    
		-----------------------------7da2e536604c8    
		Content-Disposition: form-data; name="file1"; filename="D:/haha.txt"    
		Content-Type: text/plain    
		     
		haha    
		hahaha    
		-----------------------------7da2e536604c8    
		Content-Disposition: form-data; name="file2"; filename="D:/huhu.txt"    
		Content-Type: text/plain    
		     
		messi     
		huhu    
		-----------------------------7da2e536604c8--    */		
		String resultTxt="";
		String end = "\r\n";  
        String twoHyphens = "--";  
        String boundary = "footfoodapplicationrequestnetwork";
        URL url = new URL(actionUrl);  
        HttpURLConnection con = (HttpURLConnection) url.openConnection();  
        // 发送POST请求必须设置如下两行    
        con.setDoInput(true);  
        con.setDoOutput(true);  
        con.setUseCaches(false);  
        con.setRequestMethod("POST");  
        con.setRequestProperty("Connection", "Keep-Alive");  
        con.setRequestProperty("Charset", "UTF-8");  
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 
        con.connect();
        DataOutputStream ds =  new DataOutputStream(con.getOutputStream());          
        //发送参数
        Set<String> keySet = pramsMap.keySet();  
        for (Iterator<String> it = keySet.iterator(); it.hasNext();) {  
        	String name = it.next();  
        	String value = pramsMap.get(name); 
	        ds.writeBytes(twoHyphens + boundary + end); 
	        ds.writeBytes("Content-Disposition: form-data; name=\"" + name +"\""+ end); 
	        ds.writeBytes(end);  
	        ds.writeBytes(value);
	        ds.writeBytes(end); 
        }
       //发送文件        	
        int inex=0;
        for (Iterator<FileItem> it = fileList.iterator(); it.hasNext();) {
        	FileItem item = it.next();
        	if (item.isFormField()) {
        	/*	System.out.println("prms:"+item.getFieldName());*/
        		continue;
        	}
            ds.writeBytes(twoHyphens + boundary + end);  
            ds.writeBytes("Content-Disposition: form-data; " +  "name=\"file"+(inex+1)+"\";filename=\"" +URLEncoder.encode(item.getName(),"utf-8") + "\"" + end);
            ds.writeBytes("Content-Type: " + item.getContentType() + end); 
            ds.writeBytes(end);  
            ds.write(item.get()); 
            ds.writeBytes(end);
        }
        ds.writeBytes(twoHyphens + boundary + twoHyphens + end); 
        ds.flush();         
		//ds.close();
		InputStream is = con.getInputStream();
		BufferedReader br =new BufferedReader(new InputStreamReader(is));		
		String readLine =null;
		while((readLine =br.readLine()) !=null){			
			resultTxt = resultTxt + readLine;
		}	
		ds.close();
		br.close();
		con.disconnect();
		return resultTxt;
	}
	/**
	 * 通过HttpURLConnection Post 上传文件
	 * @param files
	 * @param actionUrl
	 * @param pramsMap
	 * @return
	 * @throws Exception
	 */
	public synchronized static String uploadFileByPost(MultipartFile[] files, String actionUrl, Map<String,String> pramsMap) throws Exception {

		String resultTxt="";
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "footfoodapplicationrequestnetwork";
		URL url = new URL(actionUrl);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		// 发送POST请求必须设置如下两行
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false);
		con.setRequestMethod("POST");
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");
		con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
		con.connect();
		DataOutputStream ds =  new DataOutputStream(con.getOutputStream());
		//发送参数
		Set<String> keySet = pramsMap.keySet();
		for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
			String name = it.next();
			String value = pramsMap.get(name);
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; name=\"" + name +"\""+ end);
			ds.writeBytes(end);
			ds.writeBytes(value);
			ds.writeBytes(end);
		}
		//发送文件
		int inex=0;
		for (int i=0;i<files.length;i++) {

			MultipartFile file=files[i];
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; " +  "name=\"file"+(inex+1)+"\";filename=\"" +URLEncoder.encode(file.getOriginalFilename(),"utf-8") + "\"" + end);
			ds.writeBytes("Content-Type: " + file.getContentType() + end);
			ds.writeBytes(end);
			ds.write(file.getBytes());
			ds.writeBytes(end);
		}
		ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
		ds.flush();
		//ds.close();
		InputStream is = con.getInputStream();
		BufferedReader br =new BufferedReader(new InputStreamReader(is));
		String readLine =null;
		while((readLine =br.readLine()) !=null){
			resultTxt = resultTxt + readLine;
		}
		ds.close();
		br.close();
		con.disconnect();
		return resultTxt;
	}
	/**
	 * 通过HttpURLConnection Post 上传文件
	 * @param dataByte
	 * @param actionUrl
	 * @param pramsMap
	 * @param contentType
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public synchronized static String uploadFileByPost(byte[] dataByte, String actionUrl,Map<String,String> pramsMap,String contentType,String fileName) throws Exception {
		/*-----------------------------7da2e536604c8    
		Content-Disposition: form-data; name="username"    
		     
		hello word    
		-----------------------------7da2e536604c8    
		Content-Disposition: form-data; name="file1"; filename="D:/haha.txt"    
		Content-Type: text/plain    
		     
		haha    
		hahaha    
		-----------------------------7da2e536604c8    
		Content-Disposition: form-data; name="file2"; filename="D:/huhu.txt"    
		Content-Type: text/plain    
		     
		messi     
		huhu    
		-----------------------------7da2e536604c8--    */		
		String resultTxt="";
		String end = "\r\n";  
        String twoHyphens = "--";  
        String boundary = "footfoodapplicationrequestnetwork";
        URL url = new URL(actionUrl);  
        HttpURLConnection con = (HttpURLConnection) url.openConnection();  
        // 发送POST请求必须设置如下两行    
        con.setDoInput(true);  
        con.setDoOutput(true);  
        con.setUseCaches(false);  
        con.setRequestMethod("POST");  
        con.setRequestProperty("Connection", "Keep-Alive");  
        con.setRequestProperty("Charset", "UTF-8");  
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 
        con.connect();
        DataOutputStream ds =  new DataOutputStream(con.getOutputStream());          
        //发送参数
        Set<String> keySet = pramsMap.keySet();  
        for (Iterator<String> it = keySet.iterator(); it.hasNext();) {  
        	String name = it.next();  
        	String value = pramsMap.get(name); 
	        ds.writeBytes(twoHyphens + boundary + end); 
	        ds.writeBytes("Content-Disposition: form-data; name=\"" + name +"\""+ end); 
	        ds.writeBytes(end);  
	        ds.writeBytes(value);
	        ds.writeBytes(end); 
        }
       //发送文件        	
        int inex=0;
        
        ds.writeBytes(twoHyphens + boundary + end);  
        ds.writeBytes("Content-Disposition: form-data; " +  "name=\"file"+(inex+1)+"\";filename=\"" +URLEncoder.encode(fileName,"utf-8") + "\"" + end);
        ds.writeBytes("Content-Type: " + contentType + end); 
        ds.writeBytes(end);  
        ds.write(dataByte); 
        ds.writeBytes(end);
       
        ds.writeBytes(twoHyphens + boundary + twoHyphens + end); 
        ds.flush();         
		//ds.close();
		InputStream is = con.getInputStream();
		BufferedReader br =new BufferedReader(new InputStreamReader(is));		
		String readLine =null;
		while((readLine =br.readLine()) !=null){			
			resultTxt = resultTxt + readLine;
		}	
		ds.close();
		br.close();
		con.disconnect();
		return resultTxt;
	}
	/**
    *
    * @param url
    * @param params
    * @return
    */
   public static String initParams(String url, Map<String, Object> params,String encoding){
       if (null == params || params.isEmpty()) {
           return url;
       }
       StringBuilder sb = new StringBuilder(url);
       if (url.indexOf("?") == -1) {
           sb.append("?");
       } else {
           sb.append("&");
       }
       boolean first = true;
       for (Entry<String, Object> entry : params.entrySet()) {
           if (first) {
               first = false;
           } else {
               sb.append("&");
           }
           String key = entry.getKey();
           Object value = entry.getValue();
           sb.append(key).append("=");
           if (value!=null && value.toString().trim().length()>0) {
               try {
                   sb.append(URLEncoder.encode(value.toString(), encoding));
               } catch (UnsupportedEncodingException e) {
                   e.printStackTrace();                   
               }
           }
       }
       return sb.toString();
   }
   

}
